package controller;

import common.Message;
import common.MessageType;
import common.User;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.Stage;
import ui.Main;
import util.PhoneCheck;
import util.SetDatePicker;

import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ResourceBundle;

public class InfoController implements Initializable {
    private User user=Main.userClientService.getUser();
    private static Socket socket=Main.userClientService.getSocket();
    @FXML
    private TextField name;
    @FXML
    private DatePicker birth;
    @FXML
    private Label number;
    @FXML
    private TextField phone;
    @FXML
    private Label email;
    @Override
    public void initialize(URL location, ResourceBundle resources){
        name.setText(user.getName());
        SetDatePicker.setDatePicker(birth);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.parse(user.getBirth(), formatter);
        birth.setValue(localDate);
        number.setText(user.getNumber());
        phone.setText(user.getPhone());
        email.setText(user.getId());
    }
    @FXML
    private Label error;
    @FXML
    private Label infonull;
    @FXML
    public void Ok(){
        if(!PhoneCheck.checkPhone(phone.getText())){
            error.setText("手机号格式错误");
            return;
        }
        if(user.getName().equals("")&&user.getBirth().equals("")&&user.getPhone().equals("")){
            infonull.setText("资料未填写完全");
            return;
        }
        if(user.getName().equals(name.getText())&&user.getBirth().equals(String.valueOf(birth.getValue()))&&user.getPhone().equals(phone.getText())){
            return;
        }
        error.setText("手机号格式正确");
        user.setName(name.getText());
        MainController.nameProperty.set(user.getName());
        user.setPhone(phone.getText());
        user.setBirth(String.valueOf(birth.getValue()));
        try {
            ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
            Message ms=new Message();
            ms.setState(MessageType.change_info);//发送请求
            oos.writeObject(ms);
            oos.writeObject(user);
        } catch (Exception e) {
            System.out.println("修改资料失败");
        }finally {
            Stage stage=(Stage) error.getScene().getWindow();
            stage.close();
        }
    }
    @FXML
    private Button cancel;
    @FXML
    public void Cancel(){
        Stage stage=(Stage) cancel.getScene().getWindow();
        stage.close();
    }
}
